package com.ymttest.datadriver;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.json.JSONObject;

import com.ymttest.utils.JsonBeanHelper;

public class AssertDataImpl implements AssertData{
	private Map<String,Object> paramMap = new HashMap<String,Object>();
	private List<DBCheckDataBean> sqlCheckList = new ArrayList<DBCheckDataBean>();
	private List<DBCheckDataBean>  mongoCheckList = new ArrayList<DBCheckDataBean>();
	
	public AssertDataImpl(){
		
	}
	
	public AssertDataImpl(JSONObject jsonObject, Map<String, String> caseAssertMap){
		initData(jsonObject,caseAssertMap);
	}
	
	private void initData(JSONObject jsonObject,Map<String, String> caseAssertMap){
		if (caseAssertMap !=null){
			for(String K:caseAssertMap.keySet()){
				String V = caseAssertMap.get(K);
				boolean isKeyRight = false;
				String[] _Kargs = K.split("\\.");
				if (_Kargs[0].equals(AssertData.key_Param)){
					isKeyRight = true;
					if (_Kargs.length==2){
						paramMap.put(_Kargs[1], JsonBeanHelper.getJsonBeanNodeObj(jsonObject, V));
					}else{
						throw new IllegalArgumentException("Assert - if key is "+ AssertData.key_Param+", it should be param.xxx ");
					}
				}
				
				if (_Kargs[0].equals(AssertData.key_Sql)){
					isKeyRight = true;
					if (_Kargs.length==3){
						String tableName = _Kargs[1];
						String searchStr = _Kargs[2].replaceAll("\\(", "").replaceAll("\\)", "");
						String assertStr = V.replaceAll("\\(", "").replaceAll("\\)", "");
						sqlCheckList.add(new DBCheckDataBean(tableName, searchStr, assertStr));
					}else{
						throw new IllegalArgumentException("Assert - if key is " + AssertData.key_Sql + ", it should be param.xxx.xxx ");
					}
				}
				
				if (_Kargs[0].equals(AssertData.key_Mongo)){
					isKeyRight = true;
					if (_Kargs.length==3){
						String tableName = _Kargs[1];
						String searchStr = _Kargs[2].replaceAll("\\(", "").replaceAll("\\)", "");
						String assertStr = V.replaceAll("\\(", "").replaceAll("\\)", "");
						mongoCheckList.add(new DBCheckDataBean(tableName, searchStr, assertStr));
					}else{
						throw new IllegalArgumentException("Assert - if key is " + AssertData.key_Mongo + ", it should be param.xxx.xxx ");
					}
				}
				
				//check invalid key name
				if (!isKeyRight){
					throw new IllegalArgumentException("Assert - if key [" + K + "] is invalid and must be one of "
							+AssertData.key_Param+","+AssertData.key_Sql+","+AssertData.key_Mongo);
				}
			}
				
			
		}
	}
	
	
	
	@Override
	public Map<String, Object> getParamMap() {
		return paramMap;
	}

	@Override
	public List<DBCheckDataBean> getSqlCheckList() {
		return sqlCheckList;
	}

	@Override
	public List<DBCheckDataBean> getMongoCheckList() {
		return mongoCheckList;
	}

}
